package com.fix.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import com.fix.entity.Users;

@Component
public class ChatHandShakeInterceptor implements HandshakeInterceptor {

	// 握手之前,若返回false ，不建立连接
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		
		ServletServerHttpRequest req =(ServletServerHttpRequest)request;
		HttpSession session  = req.getServletRequest().getSession(false);
		Users user = (Users)session.getAttribute("loginuser");
		if (user != null) {
			attributes.put("socketuser", user);  //存到websocket session里
			System.out.println(user.getUid()+"---websocket:用户---" +user.getuName());
		}else{
			System.out.println("握手失败...");
			return false;
		}
		
		System.out.println("握手开始...");
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		// TODO Auto-generated method stub
		
	}

}
